package com.inpion.board.logic.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;

import com.inpion.board.criteria.BoardCriteria;
import com.inpion.board.dao.BoardDao;
import com.inpion.board.entity.Board;
import com.inpion.board.entity.BoardItem;
import com.inpion.board.entity.Label;
import com.inpion.board.logic.BoardLogic;
import com.inpion.framework.context.annotations.Logic;
import com.inpion.framework.exception.RootException;
import com.inpion.framework.util.Paging;

@Logic(value="com.inpion.board.logic")
public class BoardLogicImpl implements BoardLogic {
	
	@Autowired
	BoardDao boardDao;
	
	/* (non-Javadoc)
	 * @see com.inpion.board.logic.BoardLogic#createBoard(com.inpion.board.entity.Board)
	 */
	@Override
	public String createBoard(Board board) {
		String newBoardNo = boardDao.selectNewBoardNo();
		
		board.setBoardNo(newBoardNo);
		
		boardDao.insertBoard(board);
		
		return newBoardNo;
	}
	
	@Override
	public Board getBoard(String boardNo) {
		Board foundBoard = boardDao.selectBoard(boardNo);
		
		foundBoard.setLabels(boardDao.selectLabelListByBoardNo(boardNo));
		
		return foundBoard;
	}
	
	@Override
	public String createLabel(Label label) {
		String newLabelNo = boardDao.selectNewLabelNo();
		
		label.setLabelNo(newLabelNo);
		
		boardDao.insertLabel(label);
		
		return newLabelNo;
	}
	
	/* (non-Javadoc)
	 * @see com.inpion.board.logic.BoardLogic#createBoardItem(com.inpion.board.entity.BoardItem)
	 */
	@Override
	public String createBoardItem(BoardItem boardItem) {
		String newBoardItemNo = boardDao.selectNewBoardItemNo();
		
		boardItem.setItemNo(newBoardItemNo);
		
		boardDao.insertBoardItem(boardItem);
		
		return newBoardItemNo;
	}
	
	/* (non-Javadoc)
	 * @see com.inpion.board.logic.BoardLogic#getBoardItems(com.inpion.board.criteria.BoardCriteria)
	 */
	@Override
	public Paging<BoardItem> getBoardItems(BoardCriteria criteria) {
		long totalNumberOfItems = boardDao.selectBoardItemCount(criteria);
		List<BoardItem> items = boardDao.selectBoardItemList(criteria);
		
		Paging<BoardItem> result = new Paging<BoardItem>();
		result.setPage(criteria.getPage());
		result.setPageSize(criteria.getPageSize());
		result.setTotalNumberOfItems(totalNumberOfItems);
		result.setItems(items);
		
		return result;
	}

	/* (non-Javadoc)
	 * @see com.inpion.board.logic.BoardLogic#removeBoardItem(java.lang.String, java.lang.String)
	 */
	@Override
	public void removeBoardItem(String boardItemNo, String userNo) {
		BoardItem foundBoardItem = boardDao.selectBoardItem(boardItemNo);
		
		if (!foundBoardItem.getAuthor().getUserNo().equals(userNo))
			throw new RootException("게시물 작성자만 게시물을 삭제할 수 있습니다.");
		
		boardDao.deleteBoardItem(boardItemNo);
	}

}
